import {
  BadRequestException,
  Controller,
  Get,
  Post,
  Req,
  UploadedFile,
  UseInterceptors,
  Query,
} from '@nestjs/common';
import { ApiOperation, ApiConsumes, ApiTags, ApiBody } from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import { FileNameEncodePipe } from '~/common/pipes/file-name-encode.pipe';
import { MinioService } from './minio.service';
import { MinioUploadDto } from './minio.dto';
import { AuthUser } from '~/modules/auth/decorators/auth-user.decorator';

@ApiTags('System - minio模块')
@Controller('minio')
export class MinioController {
  constructor(private readonly _minioService: MinioService) {}

  // 参考文档
  // https://juejin.cn/post/7477412987210514432

  @Post('upload')
  @ApiOperation({ summary: '上传' })
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FileInterceptor('file'))
  @ApiBody({
    type: MinioUploadDto,
  })
  async upload(
    @UploadedFile(new FileNameEncodePipe()) file: Express.Multer.File,
    @AuthUser() user: IAuthUser
  ) {
    try {
      const path = await this._minioService.saveFile(file, user.uid);
      return {
        filename: path,
      };
    } catch (error) {
      console.log(error);
      throw new BadRequestException('上传失败');
    }
  }

  @Get('delete')
  @ApiOperation({
    summary: '根据文件名称+后缀删除文件，例如《二次续签附件.pdf》',
  })
  async deleteFile(@Query('fileName') fileName: string) {
    return await this._minioService.deleteFile(fileName);
  }

  @Get('getbucketlist')
  @ApiOperation({ summary: '获取某个存储桶的所有内容' })
  async getBucketList(bucketName: string) {
    return await this._minioService.getDirectoryStructure(bucketName);
  }
}
